package com.zimi.file.controller;

import com.zimi.file.model.SysFile;
import com.zimi.file.service.FileInfoService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static com.zimi.file.controller.FileApi.fileView;

@Slf4j
@RestController
public class AssetsApi {

    private final FileInfoService fileInfoService;

    @Autowired
    public AssetsApi(FileInfoService fileInfoService) {
        this.fileInfoService = fileInfoService;
    }

    /**
     * 原文件查看
     */
    @RequestMapping(value = "assets/**")
    public ResponseEntity<InputStreamResource> assets(HttpServletRequest request) {
        String servletPath=request.getServletPath();
        int ps=servletPath.indexOf("/")+1;
        int pl=servletPath.lastIndexOf("/")+1;
        String path=servletPath.substring(ps,pl);
        String name=servletPath.substring(pl);
        SysFile sysFile = null;
        try {
            sysFile = fileInfoService.assets(path,name);
        } catch (IOException ignored) {
        }
        return fileView(sysFile);
    }
}
